package com.example.coreshopapp.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.coreshopapp.R;
import com.example.coreshopapp.app.Constants;
import com.example.coreshopapp.base.BaseActivity;
import com.example.coreshopapp.bean.AddMemberReq;
import com.example.coreshopapp.bean.MemberData;
import com.example.coreshopapp.bean.PayMethodData;
import com.example.coreshopapp.databinding.ActivityMemberBinding;
import com.example.coreshopapp.fragment.AddMemberFragment;
import com.example.coreshopapp.keyboard.widget.CustomKeyboard;
import com.example.coreshopapp.task.MemberTask;
import com.example.coreshopapp.utils.LoadingUtils;
import com.example.coreshopapp.utils.PhoneRegexUtils;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MemberActivity extends BaseActivity {
    private CustomKeyboard numKeybord;
    private ActivityMemberBinding binding;
    private ArrayList<Map<String, String>> valueList;
    private Animation enterAnim;
    private Animation exitAnim;
    private MemberTask memberTask;
    private MemberData memberInfo;
    private AddMemberFragment addMemberFragment;
    private AddMemberReq addMemberReq;

    @SuppressLint("HandlerLeak")
    private Handler searchHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
            switch (msg.what) {
                case 9900:
                    List<MemberData> memberList = JSON.parseArray(msg.obj.toString(), MemberData.class);
                    if (memberList.size() > 0) {
                        memberInfo = memberList.get(0);
                        settingInfo();
                    } else {
                        Toast.makeText(MemberActivity.this, "当前号码未注册会员", Toast.LENGTH_LONG).show();
                    }
                    break;
                case 9901:
                    Toast.makeText(MemberActivity.this, "获取失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    Toast.makeText(MemberActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    gotoActivityFinish(LoginActivity.class);
                    Toast.makeText(MemberActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
            super.handleMessage(msg);
        }
    };
    @SuppressLint("HandlerLeak")
    private Handler addMemberHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
            switch (msg.what) {
                case 9900:
                    Toast.makeText(MemberActivity.this, "新增成功", Toast.LENGTH_LONG).show();
                    addMemberFragment.dismiss();
                    if (binding.etNumber.getText().toString().isEmpty()) {
                        binding.etNumber.setText(addMemberReq.getMobile());
                    }
                    break;
                case 9901:
                    Toast.makeText(MemberActivity.this, "获取失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    Toast.makeText(MemberActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    gotoActivityFinish(LoginActivity.class);
                    Toast.makeText(MemberActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member);
        binding = ActivityMemberBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        hideTopBar();
        viewClick();
        initView();
    }

    private void initView() {
        enterAnim = AnimationUtils.loadAnimation(this, R.anim.push_bottom_in);
        exitAnim = AnimationUtils.loadAnimation(this, R.anim.push_bottom_out);
        binding.etNumber.setSelectAllOnFocus(true);

        numKeybord = (CustomKeyboard) findViewById(R.id.id_numkeyboard);
        numKeybord.getLayoutBack().setOnClickListener(v -> numKeybord.startAnimation(exitAnim));
        valueList = numKeybord.getValueList();
        GridView gridView = numKeybord.getGridView();
        gridView.setOnItemClickListener(onItemClickListener);
        binding.etNumber.addTextChangedListener(watcher);
        binding.etNumber.setOnClickListener(new MemberActivity.NumOnClickListener());
        binding.etNumber.setOnFocusChangeListener(new MemberActivity.NumOnFocusChangeListener());

        memberTask = new MemberTask();
        addMemberFragment = new AddMemberFragment();

        MemberData data = Constants.AppConstVars.MemberInfo;
        if (data != null) {
            memberInfo = data;
            settingInfo();
        } else {
            memberInfo = null;
        }
    }

    AddMemberFragment.SetOnSubmitClickListener addMember = addMemberReq -> {
        LoadingUtils.showProgressDialog(MemberActivity.this, "温馨提示", "加载中，请稍后");
        this.addMemberReq = addMemberReq;
        memberTask.setAddOutHandler(addMemberHandler);
        memberTask.addExecute(addMemberReq);
    };

    private void viewClick() {
        binding.btnCancelMember.setOnClickListener(view -> {
            if (memberInfo == null) {
                Toast.makeText(this, "当前未绑定会员", Toast.LENGTH_SHORT).show();
                return;
            }
            memberInfo = null;
            Constants.AppConstVars.MemberInfo = null;
            settingInfo();
        });
        binding.btnAddMember.setOnClickListener(view -> {
            addMemberFragment.setOnSubmitClickListener(addMember);
            addMemberFragment.show(getSupportFragmentManager(), addMemberFragment.getTag());
        });
        binding.btnSubmit.setOnClickListener(view -> {
            if (memberInfo == null) {
                showtoast(this, "请先搜索会员");
                return;
            }
            Constants.AppConstVars.MemberInfo = memberInfo;
            Toast.makeText(this, "绑定成功", Toast.LENGTH_SHORT).show();
        });
    }

    // s输入的值赋值valueList
    private AdapterView.OnItemClickListener onItemClickListener = (adapterView, view, position, l) -> {
        CustomKeyboard.OnNumKeyItemClick(binding.etNumber, position, valueList);
    };

    public void onSearch(View view) {
//        Log.d( "onSearch: ",);
        String phone = binding.etNumber.getText().toString().trim();
        if (!PhoneRegexUtils.isValidPhone(phone)) {
            showtoast(this,"请输入正确的手机号");
            return;
        }
//        if (phone.length() < 11) {
//            showShortToast("请输入正确的手机号");
//            return;
//        }
        LoadingUtils.showProgressDialog(MemberActivity.this, "温馨提示", "加载中，请稍后");
        HashMap<String, String> key = new HashMap<>();
        memberTask.setSearchOutHandler(searchHandler);
        key.put("key", phone);
        memberTask.execute(key);
    }

    private class NumOnFocusChangeListener implements View.OnFocusChangeListener {
        public void onFocusChange(View v, boolean hasFocus) {
            try {
                if (hasFocus) {
                    hideAllInputMethod(MemberActivity.this);
                    binding.idNumkeyboard.setVisibility(View.VISIBLE);
                }
            } catch (Exception e) {
                Log.i("错误:", e.getMessage());
            }
        }
    }

    private class NumOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            hideAllInputMethod(MemberActivity.this);
            numKeybord.setFocusable(true);
            numKeybord.setFocusableInTouchMode(true);
            numKeybord.startAnimation(enterAnim);
            numKeybord.setVisibility(View.VISIBLE);
        }
    }

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
//            getRefundPay();
        }
    };


    private void settingInfo() {
        binding.tvName.setText(memberInfo != null ? memberInfo.getNickName() : "");
        binding.tvPhone.setText(memberInfo != null ? memberInfo.getMobile() : "");
        binding.tvSex.setText(memberInfo != null ? memberInfo.getSexName() : "");
        binding.tvBirthday.setText(memberInfo != null ? memberInfo.getBirthday() : "");
        binding.tvGrade.setText(memberInfo != null ? memberInfo.getGradeName() : "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}